
// const io = require('./socket.io.slim.js');

var io = require('../miniprogram_npm/wxapp-socket.io-client/index.js')

console.log('io');
console.log(io)

class Socket {
  connection = null;
  ops = {};
  constructor(options = {}) {
    this.ops = { ...options };
    this.openConnection();
    return this.connection;
  }

  openConnection() {
    try {
      const url = this.ops.url || 'ws://127.0.0.1:3006/clint';
      // this.connection = io(url, {
      //   transports: ['websocket']
      // });

      this.connection = io(url, {
        transports: ['websocket'], // 此项必须设置
        transportOptions: {
          websocket: {
            extraHeaders: { // 可选，小程序 WebSocket API 允许设置的 header
              'x-client-id': 'abc',
            },
            protocols: ['custom-protocol'] // 可选，子协议数组
          },
        },
      })

      // console.log('connection 3006');
    } catch (error) {
      console.log('open connection error');
    }

    this.connection.on('connect', this.onConnect);
    this.connection.on('error', this.onError);
    this.connection.onclose = this.handleClose;
    this.connection.on('disconnect', this.onDisconnect);
    this.connection.on('message', this.onMessage);
    this.connection.on('onuserconnect', this.onConnectMessage);
    this.connection.on('update', this.onUpdate);
  }

  onConnect = () => {
    console.log('in on connent');
    this.connection.emit('userconnect', 'success');
  };

  onDisconnect = () => {
    console.log('in disconnect');
    setTimeout(this.openConnection.bind(this), 500);
  };

  onMessage = (msg) => {
    this.ops.onMessage && this.ops.onMessage(msg);
  };

  onConnectMessage = (msg) => {
    this.ops.onConnectMessage && this.ops.onConnectMessage(msg);
  };

  onUpdate = (msg) => {
    this.ops.onUpdate && this.ops.onUpdate(msg);
  };

  onError = (event) => {
    console.log(`Websocket connection error: ${JSON.stringify(event)}`);
  };

  handleClose = (e) => {
    console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean);
    console.log(e);
  };

  close = () => {
    if (
      this.connection &&
      this.connection.readyState !== 'CLOSING' &&
      this.connection.readyState !== 'CLOSED'
    ) {
      this.connection.onclose = () => { };
      this.connection.onerror = () => { };
      this.connection.close();
    }
  };
}

export { Socket };
